import { reqspecslist, reqspecscount } from '../../request/api'

const state = {
    list: [],
    size: 2,
    count: 0,
    page: 1
}

const getters = {
    list(state) {
        return state.list
    },
    size(state) {
        return state.size
    },
    count(state) {
        return state.count
    },
    page(state) {
        return state.page
    },
}

const mutations = {
    changeList(state, list) {
        state.list = list
    },
    changeSize(state, size) {
        state.size = size
    },
    changeCount(state, count) {
        state.count = count
    },
    changePage(state, page) {
        state.page = page
    },
}

const actions = {
    reqLists(context, isAll = false) {
        // console.log('success');
        let params = isAll ? {} : {
            size: context.state.size,
            page: context.state.page
        }
        reqspecslist(params).then(res => {
            if (res.data.code === 200) {
                console.log('success');
                let list = res.data.list ? res.data.list : [];
                if (list.length == 0 && context.state.page != 1) {
                    context.commit('changePage', context.state.page - 1);
                    context.dispatch("reqLists");
                }
                context.commit('changeList', list)
            }
        })
    },
    reqCount(context) {
        reqspecscount().then(res => {
            if (res.data.code === 200) {
                let count = res.data.list[0].total
                context.commit('changeCount', count)
            }
        })
    },

    // 这里的page就是分页器中的回调的参数
    reqPageChange(context, page) {
        context.commit('changePage', page)
        console.log(page);
        // 注意这里调用的是此处的reqLists
        context.dispatch('reqLists')
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}